<template>
  <div class="menu-page">
    <div id="account-manage">
      <div class="account-data">
        <el-table
            ref="table"
            :data="tableData"
            @select="select"
            @select-all="selectAll"
            @selection-change="selectionChange"
            :row-style="rowStyle"
        >
          <template #empty>
            <el-empty description="nil">
            </el-empty>
          </template>

          <el-table-column type="selection"/>
              <el-table-column label="序号" width="100px">
                <template #default="scope">
                  {{ GetIndex(scope.$index) }}
                </template>
              </el-table-column>
          <el-table-column label="头像" width="100px">
            <template #default="scope">
              <el-avatar size="small" :src="scope.row.picture"/>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="姓名"/>
          <el-table-column prop="account" label="账号"/>
          <el-table-column prop="email" label="邮箱"/>
          <el-table-column prop="gender" label="性别"/>

          <el-table-column prop="status" label="状态">
            <template #default="scope">
              {{ Status(scope.row.status) }}
            </template>
          </el-table-column>
          <el-table-column prop="creatTime" label="加入时间">
            <template #default="scope">
              {{ dateFormat(scope.row.creatTime) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" fixed="right">
            <template #header>
              <el-input v-model="search" size="small" placeholder="名称查询"/>
            </template>
            <template #default="scope">
              <el-button
                  link
                  icon="Edit"
                  type="warning"
                  size="small"
                  @click="editOpt(scope.row,scope.$index)"/>
              <el-popconfirm title="确认删除?"
                             @confirm="deleteOpt(scope.row,scope.$index)"
              >
                <template #reference>
                  <el-button link icon="Delete" type="danger" size="small"/>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button
            style="width: 100%; margin-top: 10px"
            link
            icon="AddUserIcon" t
            ype="primary"
            @click="openAdd"
        >
          添加账号
        </el-button>
        <div>
          <Pages ref="accountPage" @action="paging" @change="changeSize"/>
        </div>
      </div>
    </div>
  </div>
  <el-dialog
      v-model="addflag"
      title="添加账号"
      width="20%"
      draggable
      append-to-body
      center
      :close-on-click-modal="false"
      @close="closeAdd"
  >
    <el-form
        :model="form"
        aria-autocomplete="inline"
        label-position="left"
        ref="addFormRef"
        :rules="rules"
    >
      <el-form-item label="账号" prop="account">
        <el-input v-model="form.account"/>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.name"/>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input show-password v-model="form.password"/>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="form.gender">
          <el-radio-button label="男"/>
          <el-radio-button label="女"/>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="addUser(addFormRef)">添加</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import Pages from "../../../../management-system/components/Pages.vue";
import {computed, onMounted, reactive, ref} from "vue";
import Axios from "../../../../plugins/axios";
import {dateFormat, Status} from "../../../../utils/utils";
import {sys} from "../../../../model/system";
import {ElMessage, FormInstance, FormRules} from "element-plus";

const table = ref()
const selectRow = ref<any>([])
const multiple = ref(false)
const tableData = ref<any>([])
const accountPage = ref()
const search = ref()


function editOpt(row, index) {

}

async function deleteOpt(row, index) {
  // 获取用户是否存在组织中
  let flag=await GetUserOrgList(row.id)
  if (!flag){
    ElMessage({
      type:'warning',
      message:'账号存在未退出组织'
    })
    return
  }
  console.log('del')
  Axios.post('/api/configuration/user/del',{
    Id:row.id
  }).then(response=>{
    let data:sys.Result<any> =response.data
    if (data.code==='0000'){
        init()
    }
  })
}

function GetUserOrgList(id:number) {
  return new Promise<boolean>(resolve => {
    Axios.get('/api/configuration/user/orgList',{
      params:{
        Id:id
      }
    }).then(response=>{
      let data:sys.Result<any> =response.data
      if (data.code==='0000'){
        let flag=true
        if (data.data!==null&&data.data.length>0){
          flag=false
        }
        resolve(flag)
      }else {
        resolve(false)
      }
    })
  })
}


const addflag = ref(false)
const addFormRef=ref<FormInstance>()
const form = ref({
  name: '',
  account: '',
  password: '',
  gender: ''
})

function openAdd() {
  addflag.value = !addflag.value
  form.value = {
    name: '',
    account: '',
    password: '',
    gender: '',
  }
}

function checkNull(rule: any, value: any, callback: any) {
  if (value===null||value===''){
    callback(new Error('必填'))
    return
  }
  callback()
}

const rules=reactive<FormRules>({
  name:[{validator:checkNull,trigger:'blur'}],
  account:[{validator:checkNull,trigger:'blur'}],
  password:[{validator:checkNull,trigger:'blur'}],
  gender:[{validator:checkNull,trigger:'blur'}]
})

function closeAdd() {
  addFormRef.value?.resetFields()
}

function addUser(formEl:FormInstance|undefined) {
  if (!formEl) return
  console.log(form.value)
  formEl.validate((flag)=>{
    if (flag){
// todo 添加用户接口
      Axios.post('/api/configuration/user/add', form.value).then(response => {
        let data: sys.Result<any> = response.data
        if (data.code === "0000") {
          // 添加成功
          let pageNum = accountPage.value.GetPageNum();
          let size = accountPage.value.GetSize();
          Axios.get('/api/configuration/user/accounts', {
            params: {
              page: pageNum,
              size: size
            }
          }).then(function (resp) {
            let data = resp.data;
            if (data.code === "0000") {
              SetData(data.data.rows)
            }
            accountPage.value.SetTotal(data.data.count)
          })
        }
      })
      addflag.value=!addflag.value
    }else {
      ElMessage({
        type:'warning',
        message:'补全信息'
      })
    }
  })
}


// 选中行的样式
function rowStyle({row, rowIndex}) {
  if (selectRow.value.includes(row, 0)) {
    return {"background-color": "#d5e8fa"}
  }
}

function select(selection, row) {
  if (selectRow.value.includes(row)) {
    let index = selectRow.value.findIndex(value => {
      let f = false
      f = value.name === row.name
      return f
    });
    if (index !== -1) {
      selectRow.value.splice(index, 1)
    }
  } else {
    selectRow.value.push(row)
    table.value.setCurrentRow(row)
  }
  selectRow.value = table.value.getSelectionRows()
  // 更新多选标识
  multiple.value = false
  if (selectRow.value.length > 1) {
    multiple.value = true
  }
}


function selectAll(selection) {
  selectRow.value = table.value.getSelectionRows()
  multiple.value = false
  if (selectRow.value.length > 0) {
    multiple.value = true
  }
}

function selectionChange(selection) {
  // console.log('selectionChange:',selection)
  // 全选后发生了
  multiple.value = false
  if (selectRow.value.length > 1) multiple.value = true
}

// 清空选中数据
function ClearSelectRows() {
  table.value.clearSelection()
  selectRow.value = []
  multiple.value = false
}

function SetData(data) {
  tableData.value = data
}


function paging(newPage: number, size: number) {
  // 执行翻页
  Axios.get('/api/configuration/user/accounts', {
    params: {
      page: newPage,
      size: size
    }
  }).then(function (resp) {
    let data = resp.data;
    if (data.code === "0000") {
      SetData(data.data.rows)
    }
    accountPage.value.SetTotal(data.data.count)
  })
}

function changeSize(page: number, size: number) {
  Axios.get('/api/configuration/user/accounts', {
    params: {
      page: page,
      size: size
    }
  }).then(function (resp) {
    let data = resp.data;
    if (data.code === "0000") {
      SetData(data.data.rows)
      accountPage.value.SetTotal(data.data.count)
    }
  })
}


const GetIndex = computed(() => (v: number) => {
  return accountPage.value.Index(v)
})

function init() {
  let size = accountPage.value.GetSize();
  Axios.get('/api/configuration/user/accounts', {
    params: {
      page: 1,
      size: size
    }
  }).then(function (resp) {
    let data = resp.data;
    if (data.code === "0000") {
      SetData(data.data.rows)
      accountPage.value.SetTotal(data.data.count)
    }
  })
}

onMounted(init)
</script>

<style scoped>
#account-manage {
  width: 100%;
  display: flex;
  flex-direction: column;
}

.account-data {
  width: 97%;
  margin: auto;
  height: 800px;
  box-shadow: var(--el-box-shadow-lighter);
  background-color: white;
}
</style>